<template>
  <div class="FilePreview">
    <a-modal :transitionName="''" :maskTransitionName="''" :mask="false" destroyOnClose centered width="100%"
             wrap-class-name="full-modal" ref="userOrgPosSelectorRef" v-model:visible="visible" @cancel="modalClear">
      <template #title>
        <div style="display: flex;flex-direction: column;justify-content: center;align-items: center">
          <div style="width: 100%; text-align: center">{{ _fileName }}</div>
        </div>
      </template>
      <template #footer>
        <div style="display: flex; flex-direction: row; justify-content: center; align-items: center; padding: 12px">
          <a-space wrap>
            <a-button :icon="h(SyncOutlined)" type="primary" block @click="refresh">刷新</a-button>
            <a-button :icon="h(PlusCircleOutlined)" type="primary" block v-if="attachmentType == 'IMAGE'"
                      @click="imageCtrl('放大')">放大
            </a-button>
            <a-button :icon="h(MinusCircleOutlined)" type="primary" v-if="attachmentType == 'IMAGE'"
                      @click="imageCtrl('缩小')">缩小
            </a-button>
            <a-button :icon="h(UndoOutlined)" type="primary" v-if="attachmentType == 'IMAGE'"
                      @click="imageCtrl('旋转')">旋转
            </a-button>
            <a-button :icon="h(LogoutOutlined)" type="link" block @click="modalClear">退出</a-button>
          </a-space>
        </div>
      </template>
      <div
          style="width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: flex-start; align-items: flex-start">
        <div
            style="width: 100%; height: 20%; display: flex; flex-direction: row; justify-content: center; align-items: center"
            v-if="loading">
          <a-spin :spinning="loading && !showProgress" :indicator="indicator"></a-spin>
          <a-progress v-if="showProgress" type="circle" :percent="progress" />
        </div>
        <iframe v-if="showIframe" v-show="!loading" ref="iframe" width="100%" height="100%" :src="src"></iframe>
      </div>
    </a-modal>
  </div>
</template>
<script setup name="FilePreview">
import {h} from 'vue'
import {
  LoadingOutlined,
  SyncOutlined,
  PlusCircleOutlined,
  MinusCircleOutlined,
  UndoOutlined,
  LogoutOutlined
} from '@ant-design/icons-vue'
import downloadFile from "@/utils/downloadFile.js";
//import { ref } from 'vue'
const indicator = h(LoadingOutlined, {
  style: {
    fontSize: '34px'
  },
  spin: true
})
let showProgress = ref(false)
let progress = ref(0)
let iframeHost = __APP_ENV__.VITE_PREVIEW_HOST
let iframeAddress = __APP_ENV__.VITE_PREVIEW_ADDRESS
let visible = ref(false)
let loading = ref(true)
let address = ref(iframeAddress)
let iframe = ref()
let _fileName = ref(undefined)
let _id = ref(undefined)
let _type = ref(undefined)
let showIframe = ref(true)
let attachmentType = ref(undefined)
let src = ref('')
const imageCtrl = (type) => {
  try {
    iframe.value.contentWindow.postMessage(
        JSON.stringify({
          attachmentCtrl: {
            type
          }
        }),
        iframeHost
    )
  } catch (e) {
  }
}
const refresh = () => {
  showIframe.value = false
  loading.value = true
  setTimeout(() => {
    showIframe.value = true
    setData({id: _id.value, fileName: _fileName.value, type: _type.value})
  }, 50)
}
const showModal = () => {
  showIframe.value = true
  visible.value = true
}
const modalClear = (e) => {
  window.removeEventListener('message', listenFileLoad)
  visible.value = false
  showIframe.value = false
  loading.value = true
}
const listenFileLoad = (res) => {
  try {
    let data = JSON.parse(res.data)
    if (data.event == 'loading' && data.bool === true) {
      loading.value = true
    } else if (data.event == 'loading' && data.bool === false) {
      loading.value = false
    } else if (data.event == 'loading' && data.bool === false && data.errorMsg) {
      loading.value = false
    } else if (data.event == 'progress' && data.hasOwnProperty('percentComplete') && !data.errorMsg) {
      showProgress.value = true
      progress.value = data.percentComplete
      if (progress.value === 100) {
        setTimeout(() => {
          showProgress.value = false
        }, 500)
      }
    }
  } catch (e) {
  }
}
const setData = ({id, type, fileName, lengthComputable}) => {
  showProgress.value = false
  progress.value = 0
  if (/(\.gif|\.jpeg|\.png|\.jpg|\.bmp)/gi.test(fileName)) {
    attachmentType.value = 'IMAGE'
  } else if (/(\.pdf)/gi.test(fileName)) {
    attachmentType.value = 'PDF'
  } else if (/(\.doc|\.docx|\.xls|\.xlsx|\.ppt|\.pptx)/gi.test(fileName)) {
    attachmentType.value = 'WORD'
  } else if (/(\.txt)/gi.test(fileName)) {
    attachmentType.value = 'TXT'
  } else {
    attachmentType.value = 'NO_TYPE'
  }
  loading.value = true
  _fileName.value = fileName
  _id.value = id
  _type.value = type
  window.removeEventListener('message', listenFileLoad)
  window.addEventListener('message', listenFileLoad)
  showModal()
  return new Promise((resolve, reject) => {
    downloadFile.fileGetInfo(id, type, fileName, (xhr) => {
      src.value = address.value + '?token=' + xhr.token + '&fileName=' + xhr.fileName + '&url=' + xhr.url + '&lengthComputable=' + lengthComputable
      console.log('src.value------------------>', src.value)
    })
  })
}
defineExpose({
  showModal,
  modalClear,
  setData
})
</script>
<style lang="less" scoped>
.FilePreview {
}
</style>
<style lang="less">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
    padding: 0;
  }
  .ant-modal-footer,
  .ant-modal-header {
    background-color: #f5f5f5;
  }
}
</style>
